// key-value 模型
public class HashBucket {
    private static class Node {
        private int key;
        private int value;
        Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public int put(int key, int value) {
        int index = key % array.length;
        Node cur = array[index];

        while (cur != null) {
            if(cur.key == key) {
                cur.value = value;  //查看桶里是否有key值，有的话只需要改变value值
                return key;
            }
            cur = cur.next;

        }
        //头插法
        Node node = new Node(key,value);
        node.next = array[index];
        array[index] = node;
        size++;

        if(loadFactor() >= 0.75) {
            resize(); // 扩容
        }

        return key;
    }


    private void resize() {
        Node[] tempArr = new Node[2*array.length]; //创建新的长度的数组

        for(int i = 0 ; i < array.length ; i++) { //将原来的数依次添加进新的数组
            Node cur = array[i];

            while (cur != null) {
                Node curNext = cur.next;  //记录下一结点地址
                int newIndex  = cur.key % tempArr.length;
                cur.next = tempArr[newIndex];
                tempArr[newIndex] = cur;
                cur = curNext;
            }
        }

        array = tempArr;
    }


    private double loadFactor() {
        return size * 1.0 / array.length;
    }


    public HashBucket() {
        array = new Node[DEFAULT_SIZE];
    }


    public int get(int key) {
        int index = key % array.length;

        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.value;
            }
            cur = cur.next;
        }
        return -1;
    }
}
